package com;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("CorsFilter .....");
        //允许跨域访问，通过response对象写回一些跨域访问的头信息
        HttpServletResponse hresp = (HttpServletResponse) servletResponse;
        HttpServletRequest hreq = (HttpServletRequest) servletRequest;
        //跨域
        hresp.setHeader("Access-Control-Allow-Origin", "*");
        //跨域 Header
        hresp.setHeader("Access-Control-Allow-Methods", "*");
        hresp.setHeader("Access-Control-Allow-Headers", "*");
        // 浏览器是会先发一次options请求，如果请求通过，则继续发送正式的post请求
        // 配置options的请求返回
        if (hreq.getMethod().equals("OPTIONS")) {
            hresp.setStatus(HttpServletResponse.SC_OK);
            // hresp.setContentLength(0);
            hresp.getWriter().write("OPTIONS returns OK");
            return;
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}